package com.hospital.controller;

import com.hospital.common.Result;
import com.hospital.entity.Registration;
import com.hospital.entity.MedicalRecord;
import com.hospital.entity.Prescription;
import com.hospital.entity.User;
import com.hospital.service.RegistrationService;
import com.hospital.service.MedicalRecordService;
import com.hospital.service.PrescriptionService;
import com.hospital.service.UserService;
import com.hospital.service.FileService;
import com.hospital.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 患者业务控制器（专注患者相关业务）
 *
 * @author Hospital Management System
 */
@Api(tags = "患者业务管理")
@RestController
@RequestMapping("/patient")
@RequiredArgsConstructor
public class UserController {

    private final RegistrationService registrationService;
    private final MedicalRecordService medicalRecordService;
    private final PrescriptionService prescriptionService;
    private final UserService userService;
    private final FileService fileService;

    @ApiOperation("预约挂号")
    @PostMapping("/registration")
    public Result<Void> makeAppointment(@Validated @RequestBody Registration registration) {
        registrationService.makeAppointment(registration);
        return Result.success(null, "预约成功");
    }

    @ApiOperation("取消挂号")
    @PutMapping("/registration/{registrationId}/cancel")
    public Result<Void> cancelRegistration(@PathVariable Long registrationId) {
        registrationService.cancelRegistration(registrationId);
        return Result.success(null, "取消成功");
    }

    @ApiOperation("查看我的挂号记录")
    @GetMapping("/registrations")
    public Result<List<Registration>> getMyRegistrations() {
        List<Registration> registrations = registrationService.getUserRegistrations();
        return Result.success(registrations);
    }

    @ApiOperation("查看我的就诊记录")
    @GetMapping("/medical-records")
    public Result<List<MedicalRecord>> getMyMedicalRecords() {
        List<MedicalRecord> records = medicalRecordService.getUserMedicalRecords(null);
        return Result.success(records);
    }

    @ApiOperation("查看我的处方")
    @GetMapping("/prescriptions")
    public Result<List<Prescription>> getMyPrescriptions() {
        List<Prescription> prescriptions = prescriptionService.getUserPrescriptions(null);
        return Result.success(prescriptions);
    }

    @ApiOperation("查看处方详情")
    @GetMapping("/prescription/{prescriptionId}")
    public Result<Prescription> getPrescriptionDetail(@PathVariable Long prescriptionId) {
        Prescription prescription = prescriptionService.getById(prescriptionId);
        return Result.success(prescription);
    }

    @ApiOperation("查看就诊记录详情")
    @GetMapping("/medical-record/{recordId}")
    public Result<MedicalRecord> getMedicalRecordDetail(@PathVariable Long recordId) {
        MedicalRecord record = medicalRecordService.getById(recordId);
        return Result.success(record);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public Result<User> getUserInfo() {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        User user = userService.getById(currentUser.getId());
        return Result.success(user);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/updateUserInfo")
    public Result<User> updateUserInfo(@Validated @RequestBody User user) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }
        
        // 设置用户ID
        user.setId(currentUser.getId());
        
        // 调用service更新用户信息
        userService.updateById(user);
        
        // 获取更新后的用户信息
        User updatedUser = userService.getById(user.getId());
        return Result.success(updatedUser, "用户信息更新成功");
    }

    @ApiOperation("上传头像")
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        User currentUser = UserContext.getCurrentUser();
        if (currentUser == null) {
            return Result.error("用户未登录");
        }

        try {
            // 上传文件
            String avatarUrl = fileService.uploadAvatar(file);

            // 更新用户头像
            User user = new User();
            user.setId(currentUser.getId());
            user.setAvatar(avatarUrl);
            userService.updateById(user);

            // 返回头像URL
            Map<String, String> data = new HashMap<>();
            data.put("url", avatarUrl);
            return Result.success(data, "头像上传成功");
        } catch (Exception e) {
            return Result.error("头像上传失败：" + e.getMessage());
        }
    }
} 